package com.tf8.treasure.controller;

import com.alibaba.fastjson.JSONObject;
import com.tf8.treasure.enums.ReturnType;
import com.tf8.treasure.exception.RequestException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {
    private String url="E:\\tmp";
    /**
     * 预览，格式：jpeg  gif  png pdf  jpg，文件大小限制：20M
     */
    @RequestMapping(value = "/presentImage/{fileName}")
    public ResponseEntity presentImage(@PathVariable String fileName, HttpServletResponse response) throws Exception {
        log.info("图片展示入参", JSONObject.toJSONString(fileName));
        String path = url + "/" + fileName;
        File file = null;
        byte[] bytes = null;
        try {
            file = new File(path);
            bytes = FileUtils.readFileToByteArray(file);
        } catch (Exception o) {
            log.error("下载文件异常:",o);
            throw new RequestException(ReturnType.PARAM_ERROR);
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);
        headers.add("Content-Disposition", "inline; filename=\"" + fileName + "\"");
        return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
    }

}
